const bcrypt = require('bcryptjs')
const { query } = require('./config/database')

async function checkAndCreateAdmin () {
  try {
    console.log('🔍 检查现有管理员账号...')

    // 检查现有管理员
    const adminUsers = await query('SELECT * FROM users WHERE role = "admin"')
    console.log('现有管理员账号:', adminUsers)

    if (adminUsers.length === 0) {
      console.log('📝 没有找到管理员账号，正在创建...')

      // 创建管理员账号
      const hashedPassword = await bcrypt.hash('admin123', 12)

      await query(
        'INSERT INTO users (email, username, password, role, is_vip, coins) VALUES (?, ?, ?, ?, ?, ?)',
        ['admin@novel.com', '管理员', hashedPassword, 'admin', true, 9999]
      )

      console.log('✅ 管理员账号创建成功！')
      console.log('登录信息：')
      console.log('  邮箱: admin@novel.com')
      console.log('  密码: admin123')
    } else {
      console.log('✅ 已存在管理员账号')
    }

    // 再次检查所有用户
    const allUsers = await query('SELECT id, email, username, role FROM users')
    console.log('\n📋 所有用户列表:')
    console.table(allUsers)
  } catch (error) {
    console.error('❌ 操作失败:', error)
  }

  process.exit(0)
}

checkAndCreateAdmin()
